{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "18c248d27b204972",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "# Getting Started"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "679a1577cb164954",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## import the necessary packages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-20T03:59:07.334269200Z",
     "start_time": "2024-02-20T03:59:04.414596300Z"
    },
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# install package\n",
    "!pip install torch torchvision\n",
    "!pip install -U phenocv\n",
    "try:\n",
    "    import torch\n",
    "except ImportError:\n",
    "    raise ImportError(\"PyTorch is not installed. Please install it using \"\n",
    "                          \"`pip install torch torchvision` or check the \"\n",
    "                      \"https://pytorch.org/get-started/locally/ for a custom \"\n",
    "                      \"installation\")\n",
    "    \n",
    "try:\n",
    "    import phenocv\n",
    "except ImportError:\n",
    "    raise ImportError(\"PhenoCV is not installed. Please install it using \"\n",
    "                          \"`pip install phenocv`\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cde77f3c0b17e759",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## Configs"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "350f96d5b7eb18b6",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "The build of pipeline and the parameters are defined using a config and \n",
    "registry system. Here is an example of the config file for the panicle number\n",
    "analysis."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8aef450abbb19ab2",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-20T03:59:07.350113700Z",
     "start_time": "2024-02-20T03:59:07.336269600Z"
    },
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The config path is `/data/home/rlchen/micromamba/envs/phenocv_test/lib/python3.10/site-packages/phenocv/configs/sahi_panicle_num.cfg`,\n",
      "And the content is: \n",
      "#######################\n",
      "[predictor]\n",
      "@predictor = \"yolo_sahi_panicle_uav\"\n",
      "model_type = yolov8\n",
      "model_weight = https://github.com/r1cheu/phenocv/releases/download/v0.1.2/uav_panicle_yolov5n6u.pt\n",
      "device = 0\n",
      "conf = 0.25\n",
      "iou = 0.7\n",
      "slice_height = 1024\n",
      "slice_width = 1024\n",
      "overlap_height_ratio = 0.25\n",
      "overlap_width_ratio = 0.25\n",
      "\n",
      "[formatter]\n",
      "@formatter = \"naive\"\n",
      "\n",
      "#######################\n"
     ]
    }
   ],
   "source": [
    "from phenocv.utils import get_config_path\n",
    "\n",
    "config = get_config_path('sahi_panicle_num.cfg')\n",
    "print(f\"The config path is `{config}`,\\nAnd the content is: \")\n",
    "with open(config, 'r') as f:\n",
    "    print(\"#######################\")\n",
    "    print(f.read())\n",
    "    print(\"#######################\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2029b53f7905bc2",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "You can also modify the config file to fit your needs. Simply copy the content\n",
    "to a new file and modify the parameters. Note the suffix of the config file \n",
    "should be `.cfg`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d118adfda850169",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## Load Analyzer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "32929716f1001b71",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-20T03:59:07.373214700Z",
     "start_time": "2024-02-20T03:59:07.351114900Z"
    },
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from phenocv import PanicleNumAnalyzer, PanicleHeadingDateAnalyzer"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "211f25a4de47e5bc",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "if only the panicle number is needed, using the PanicleNumAnalyzer. Prepare \n",
    "all the images in one folder and run the following code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4b451fd01ed0acaf",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-20T03:59:09.143766700Z",
     "start_time": "2024-02-20T03:59:07.370114200Z"
    },
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Downloading uav_panicle_yolov5n6u.pt: 100%|██████████| 8.74M/8.74M [00:02<00:00, 4.10MiB/s]\n",
      "/data/home/rlchen/micromamba/envs/phenocv_test/lib/python3.10/site-packages/torch/cuda/__init__.py:141: UserWarning: CUDA initialization: The NVIDIA driver on your system is too old (found version 11070). Please update your GPU driver by downloading and installing a new version from the URL: http://www.nvidia.com/Download/index.aspx Alternatively, go to: https://pytorch.org to install a PyTorch version that has been compiled with your version of the CUDA driver. (Triggered internally at ../c10/cuda/CUDAFunctions.cpp:108.)\n",
      "  return torch._C._cuda_getDeviceCount() > 0\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Downloaded file to /data/home/rlchen/ProJect/phenocv/tutorial/uav_panicle_yolov5n6u.pt\n",
      "Loading model from ./uav_panicle_yolov5n6u.pt\n"
     ]
    }
   ],
   "source": [
    "# if you wish to use a bigger model, you can override the model_weight \n",
    "# parameter (uncomment the following line)\n",
    "analyzer = PanicleNumAnalyzer('sahi_panicle_num.cfg', save_file='test.csv',)\n",
    "#                              override={'predictor':{\"model_weight\": \"https://github.com/r1cheu/phenocv/releases/download/v0.1.2/uav_panicle_yolov5m6u.pt\"}})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "dd08a78f09097b73",
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--2024-02-20 13:47:53--  https://media.githubusercontent.com/media/r1cheu/phenocv/main/tutorial/test_images/20230808-GP240.jpg\n",
      "Resolving media.githubusercontent.com (media.githubusercontent.com)... 185.199.109.133, 185.199.110.133, 185.199.108.133, ...\n",
      "Connecting to media.githubusercontent.com (media.githubusercontent.com)|185.199.109.133|:443... connected.\n",
      "HTTP request sent, awaiting response... 200 OK\n",
      "Length: 11748383 (11M) [image/jpeg]\n",
      "Saving to: ‘test_images/20230808-GP240.jpg’\n",
      "\n",
      "20230808-GP240.jpg  100%[===================>]  11.20M  4.05MB/s    in 2.8s    \n",
      "\n",
      "2024-02-20 13:47:56 (4.05 MB/s) - ‘test_images/20230808-GP240.jpg’ saved [11748383/11748383]\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# prepare the image dir.\n",
    "!mkdir test_images\n",
    "!wget https://media.githubusercontent.com/media/r1cheu/phenocv/main/tutorial/test_images/20230808-GP240.jpg -P test_images/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c73d0ef0a89503f7",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-02-20T03:59:20.933282200Z",
     "start_time": "2024-02-20T03:59:09.146192Z"
    },
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing 20230808-GP240.jpg: 100%|██████████| 1/1 [00:05<00:00,  5.77s/it, num of panicle=180]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing Done, check the result: /data/home/rlchen/ProJect/phenocv/tutorial/test_images_result and test.csv\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>source</th>\n",
       "      <th>value</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>test_images/20230808-GP240.jpg</td>\n",
       "      <td>180</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                           source  value\n",
       "0  test_images/20230808-GP240.jpg    180"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# set save_pred to True to save the prediction images\n",
    "analyzer('./test_images', img_suffix='.jpg', save_pred=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3aecd780",
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.display import Image\n",
    "\n",
    "Image(filename='./test_images_result/pred/20230808-GP240.jpg')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3f2ad7e4",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
